package com.sf.dlb.service;

import com.sf.dlb.bean.UserFeedbackBean;
import com.sf.dlb.constant.ResponseConstant;
import com.sf.dlb.jpa.model.UserFeedbackInfo;
import com.sf.dlb.jpa.model.UserInfo;
import com.sf.dlb.jpa.repository.UserFeedbackRepository;
import com.sf.dlb.jpa.repository.UserInfoRepository;
import com.sf.dlb.config.Global;
import com.sf.dlb.utils.GsonUtils;
import com.sf.dlb.utils.ResultVOUtil;
import com.sf.dlb.vo.PageVO;
import com.sf.dlb.vo.ResultVO;
import com.sf.dlb.vo.UserFeedbackListVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * Created by jing.tan on 2018/5/21.
 */
@Service
public class UserFeedbackService {
    private static Logger logger = LoggerFactory.getLogger(UserFeedbackService.class);

    @Autowired
    public UserFeedbackRepository userFeedbackRepository;
    @Autowired
    public UserInfoRepository userInfoRepository;
    @Resource
    public Global global;
    /**
     * 添加反馈信息
     * @return
     */
    public ResultVO addUserFeedback(UserFeedbackBean userFeedbackBean){
        logger.info("==addUserFeedback start userRquestBean={}",GsonUtils.getInstance().toJson(userFeedbackBean));
        MultipartFile[] multipartFiles=userFeedbackBean.getFile();
        String content=userFeedbackBean.getContent();
        String contactMobile=userFeedbackBean.getContactMobile();
        String userId=userFeedbackBean.getUserId();
        StringBuffer imagePath=new StringBuffer();
        //保存图片
        if(multipartFiles!=null) {
            String absolutePath=global.getUser_image_absolute_path(userId);
            for (MultipartFile multipartFile:multipartFiles){
                String multipartFileName = UUID.randomUUID().toString()+".png";//multipartFile.getOriginalFilename();
                String localFileName = absolutePath + "/" + multipartFileName;
                String relativeFileName = new StringBuffer().append(global.getUser_image_relative_path(userId)).append("/").append(multipartFileName).toString();
                File localFile = new File(localFileName);
                try {
                    multipartFile.transferTo(localFile);
                    imagePath.append(relativeFileName).append(",");
                } catch (Exception e) {
                    e.printStackTrace();
                    logger.info("addUserFeedback 上传图片失败");
                }
            }
            logger.info("addUserFeedback imagePath " + imagePath.toString());
        }
        UserFeedbackInfo userFeedbackInfo=new UserFeedbackInfo();
        String imageStr=imagePath.toString();
        imageStr=imageStr.length()>0?imageStr.substring(0,imageStr.length()-1):imageStr;
        userFeedbackInfo.setImage(imageStr);
        userFeedbackInfo.setContent(content);
        userFeedbackInfo.setState("1");//状态：默认1
        userFeedbackInfo.setContactMobile(contactMobile);
        userFeedbackInfo.setUserId(userId);
        userFeedbackInfo.setCreateDate(new Date());
        userFeedbackInfo.setUpdateDate(new Date());
        userFeedbackRepository.save(userFeedbackInfo);
        logger.info("addUserFeedback userFeedbackInfo "+GsonUtils.getInstance().toJson(userFeedbackInfo));
        return ResultVOUtil.success();
    }
    /**
     * 用户反馈列表
     * @return
     */
    public ResultVO userFeedbackList(UserFeedbackBean reqeustData){
        logger.info("==userFeedbackList start reqeustData={}",GsonUtils.getInstance().toJson(reqeustData));
        int currentPages=reqeustData.getCurrentPages();
        int pageSize=reqeustData.getPageSize();
        Sort sort=new Sort(Sort.Direction.DESC,"createDate");
        Pageable pageable = new PageRequest(currentPages,pageSize,sort);
        Page<UserFeedbackInfo> pages = userFeedbackRepository.findByDelFlag("0",pageable);
        List<UserFeedbackInfo> userFeedbackInfos=pages.getContent();
        if(CollectionUtils.isEmpty(userFeedbackInfos)) {
            logger.info("userFeedbackList 反馈列表为空 ");
            return ResultVOUtil.error(ResponseConstant.ERROR,"反馈列表为空");
        }
        //封装Vo
        List<UserFeedbackListVO> userFeedbackListVOS = new ArrayList<>();
        PageVO pageVO=new PageVO();
        for (UserFeedbackInfo userFeedbackInfo1:userFeedbackInfos) {
            UserFeedbackListVO userFeedbackListVO=new UserFeedbackListVO();
            BeanUtils.copyProperties(userFeedbackInfo1,userFeedbackListVO);
            userFeedbackListVO.setCreateDate(userFeedbackInfo1.getCreateDate().getTime()+"");
            userFeedbackListVO.setImage(addImagePrefix(userFeedbackInfo1.getImage(),",")); //图片添加前缀；
            String[] strings=new String[]{"未开始","进行中","已解决","取消"};
            int tempIndex=Integer.valueOf(userFeedbackInfo1.getState())-1;
            userFeedbackListVO.setStateValue(strings[tempIndex]);
            //用户信息
            UserInfo userInfo=userInfoRepository.findByUserIdAndDelFlag(userFeedbackInfo1.getUserId(),"0");
            userFeedbackListVO.setUserName(userInfo.getName());
            userFeedbackListVO.setUserMobile(userInfo.getMobile());
            userFeedbackListVOS.add(userFeedbackListVO);
        }
        pageVO.setDataList(userFeedbackListVOS);
        pageVO.setPageSize(pageSize);
        pageVO.setCurrentPages(currentPages+1);//默认从0开始，返回前端要+1;
        pageVO.setFirstPage(pages.isFirst());
        pageVO.setLastPage(pages.isLast());
        pageVO.setTotalElements(pages.getTotalElements());
        pageVO.setTotalPages(pages.getTotalPages());
        return ResultVOUtil.success(pageVO);
    }
    /**
     * 用户反馈状态更新
     * @return
     */
    public ResultVO userFeedbackUpdate(UserFeedbackBean reqeustData){
        logger.info("==userFeedbackUpdate start reqeustData={}",GsonUtils.getInstance().toJson(reqeustData));
        String id=reqeustData.getId();
        String state=reqeustData.getState();
        UserFeedbackInfo userFeedbackInfo = userFeedbackRepository.findByIdAndDelFlag(Long.valueOf(id),"0");
        if(null==userFeedbackInfo){
            logger.info("userFeedbackUpdate is userFeedbackInfo null");
            return ResultVOUtil.error(ResponseConstant.ERROR,"反馈数据不存在");
        }
        userFeedbackInfo.setState(state);
        userFeedbackInfo.setUpdateDate(new Date());
        userFeedbackRepository.save(userFeedbackInfo);
        return ResultVOUtil.success();
    }
    //图片添加前缀
    public List addImagePrefix(String image,String split){
        ArrayList arrayList=new ArrayList<String>();
        if(StringUtils.isEmpty(image)){
            return arrayList;
        }
        if(StringUtils.isEmpty(split)){
            arrayList.add(global.file_public_ip +image);
            return arrayList;
        }else{
            String[] images=image.split(split);
            for (String img:images) {
                String tempImage=global.file_public_ip +img;
                arrayList.add(tempImage);
            }
            return arrayList;
        }
    }
}
